//
//  CenterTableViewController.m
//  Demo
//
//  Created by lanou3g on 14-12-6.
//  Copyright (c) 2014年 张在青. All rights reserved.
//

#import "CenterTableViewController.h"
#import "LeftTableViewController.h"

#import "FirstTableViewCell.h"
#import "SecondTableViewCell.h"
#import "ThirdTableViewCell.h"
#import "HomeModel.h"

#import "NetRequest.h"
#import "ShareDataHandle.h"
#import "AdaptHeigth.h"

#import "DetailViewController.h"
#import "DetailPictureViewController.h"
#import "DetailWebView.h"
#import "DetailPicView.h"

//下拉刷新第三方
#import "MJRefresh.h"

#define kTableViewCell @"TableViewCell"
#define kLitterCell @"LitterCell"
#define kThreePicCell @"ThirdCell"

//收藏
#import "ArchiveHandleSingle.h"
#import "DetailModel.h"


@interface CenterTableViewController () <UIScrollViewDelegate>
{
    CGPoint _point;
    BOOL _isFinish;
}


@property (nonatomic, retain)NSArray *urlArr;
@property (nonatomic, retain)UILabel *label;
@property (nonatomic, retain)UIActivityIndicatorView *activityIV;

@end

@implementation CenterTableViewController

- (void)dealloc
{
    
    [_urlArr release];
    [_passedStr release];
    [_label release];
    [_activityIV release];
    
    
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addTempTextView];
    //分别是,头条,娱乐,体育,财经,科技,军事,历史
//    self.urlArr =  @[@"T1348647909107",@"T1348648517839",@"T1348649079062",@"T1348648756099",@"T1348649580692",@"T1348649580692",@"T1368497029546"];
    
    self.passedStr = @"T1348647909107";
    _num = 0;
    
    //注册cell,分别为大cell,一张图的cell,三张图的cell
    [self.tableView registerClass:[FirstTableViewCell class] forCellReuseIdentifier:kTableViewCell];
    
    [self.tableView registerClass:[SecondTableViewCell class] forCellReuseIdentifier:kLitterCell];
    
    [self.tableView registerClass:[ThirdTableViewCell class] forCellReuseIdentifier:kThreePicCell];

    //解析数据
    [[ShareDataHandle shareDataHandle] parseDataWithCenterKeyString:self.passedStr numberStr:[NSString stringWithFormat:@"%ld",(long)_num]];
    
    //解析头条另三张图的信息
    [[ShareDataHandle shareDataHandle] parseThreePicMessage];

    
    //KVO观察值有没有改变
    [[ShareDataHandle shareDataHandle] addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    [[ShareDataHandle shareDataHandle] addObserver:self forKeyPath:@"threeArray" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    //上拉刷新,下拉加载
    [self.tableView addHeaderWithTarget:self action:@selector(dragTableDidTriggerRefresh:)];
    [self.tableView addFooterWithTarget:self action:@selector(dragTableDidTriggerLoadMore:)];
    
    
}


#pragma mark 观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"dataArray"]) {
      
        //结束菊花动画,结束时隐藏
        [self.activityIV stopAnimating];
        [self.activityIV setHidesWhenStopped:YES];
        [self.label removeFromSuperview];
        [self.tableView reloadData];
        
//        [[ShareDataHandle shareDataHandle] removeObserver:self forKeyPath:@"dataArray"];
    }
    
    if ([keyPath isEqualToString:@"threeArray"]) {
        
        [self.tableView reloadData];
        
//        [[ShareDataHandle shareDataHandle] removeObserver:self forKeyPath:@"threeArray"];
    }
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ShareDataHandle shareDataHandle].dataArray.count;
}

#pragma mark 返回cell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // NSArray *array = [[ShareDataHandle shareDataHandle].numberArr[indexPath.row] allKeys];
    
   // NSLog(@"数组: %@",array);
    HomeModel *homeModel = [ShareDataHandle shareDataHandle].dataArray[indexPath.row];
    
    if (indexPath.row == 0) {
        FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCell forIndexPath:indexPath];
        
        for (int i = 0; i < 4; i ++) {
            UIButton *button = (UIButton *)[cell.scroll viewWithTag:114+i];
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        
        //如果是头条,则有四张图片,如果不是,则只有一张图片
        if ([self.passedStr isEqualToString:@"T1348647909107"]) {
            
            cell.scroll.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 4, 180);
            cell.page.numberOfPages = 4;
            [cell writeThreeMessage];
            
            cell.scroll.delegate = self;
            
            
        }else{
            
            cell.scroll.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 180);
            UILabel *label = (UILabel *)[cell.scroll viewWithTag:105];
            label.frame = CGRectMake(cell.scroll.frame.size.width * 0.05, cell.scroll.frame.size.height * 0.9, cell.scroll.frame.size.width * 0.9, cell.scroll.frame.size.height * 0.1);
            cell.page.numberOfPages = 0;
           
        }
        
        [cell.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
        
        [cell writeMessageWithHomeModel:homeModel];
        
        return cell;
        
        
    }else if(homeModel.photosetID == nil){
        
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kLitterCell forIndexPath:indexPath];
        
        [cell writeMessage:homeModel];
        
        return cell;
       
        
        
    }else{
        
        ThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kThreePicCell forIndexPath:indexPath];
        
        [cell writeMessegeWithModel:homeModel];
        
        return cell;
    }
   
}
#pragma mark 返回tableView高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 180;
    }else{
        return 90;
    }
}
//返回头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark scrollView与page关联的代理方法

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.tableView]) {
     //   NSLog(@"tableview执行了");
    }else{
        
  //  NSLog(@"aaaa");
        
    [UIView animateWithDuration:0.2 animations:^{
    
        //找到page
        UIPageControl *page1 = (UIPageControl *)[self.view viewWithTag:113];
        int t = scrollView.contentOffset.x /    [UIScreen  mainScreen].bounds.size.width;
        if (t <= 3) {
            page1.currentPage = t;
        }else{
//            page1.currentPage = 0;
//            scrollView.contentOffset = CGPointMake(0, 0);
         //   NSLog(@"打印");
        }
        page1.currentPageIndicatorTintColor =[UIColor blackColor];
    }];
        
    }

}


#pragma mark page的方法
- (void)pageAction:(UIPageControl *)sender
{
 
    
}


#pragma mark 点击cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    HomeModel *model = [ShareDataHandle shareDataHandle].dataArray[indexPath.row];
    
    if (indexPath.row != 0) {
        
        if (model.photosetID == nil) {
         
          //  NSLog(@"点击了详情");
            
            DetailViewController *detailVC = [[DetailViewController alloc] init] ;
            
            detailVC.docidStr = model.docid;
            
            [self.navigationController pushViewController:detailVC animated:YES];
            
            [detailVC release];
            
            
        }else{
          //  NSLog(@"点击了图集");
            
            DetailPictureViewController *picVC = [[DetailPictureViewController alloc] init] ;
            
            // [picVC passValue:model.photosetID];
            
            picVC.postStr = model.photosetID;
            picVC.tempStr = model.photosetID;
            
            [self presentViewController:picVC animated:YES completion:nil];
            
            [picVC release];
            
            //自定义动画
            /*
             [UIView beginAnimations:@"animationID" context:nil];
             
             [UIView setAnimationDuration:0];
             
             [UIView setAnimationCurve:UIViewAnimationCurveLinear];
             
             [UIView setAnimationRepeatAutoreverses:NO];
             
             [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:picVC.view cache:YES];
             
             [self presentViewController:picVC animated:NO completion:nil];
             //
             
             [UIView commitAnimations];
             */
        }

    }
    
}

#pragma mark 大cell点击事件

- (void)buttonAction:(UIButton *)sender
{
    if (sender.tag == 114) {
        HomeModel *model = [ShareDataHandle shareDataHandle].dataArray[0];
        
        if (model.photosetID == nil) {
            
         //   NSLog(@"点击了详情");
            
            DetailViewController *detailVC = [[DetailViewController alloc] init] ;
            detailVC.docidStr = model.docid;
            
            [self.navigationController pushViewController:detailVC animated:YES];
            
         //   [detailVC release];
            
        }else{
        //    NSLog(@"点击了图集");
            
            DetailPictureViewController *picVC = [[DetailPictureViewController alloc] init] ;
            
           // [picVC passValue:model.photosetID];
            
            picVC.postStr = model.photosetID;
            picVC.tempStr = model.photosetID;
            
            [self presentViewController:picVC animated:YES completion:nil];
           // [self.navigationController pushViewController:picVC animated:YES];
            
          //  [picVC release];
        }

    }
    
    for (int i = 0; i < 3; i++) {
        
        if(sender.tag == 115 + i){
            
            HomeModel *hModel = [ShareDataHandle shareDataHandle].threeArray[i];
//            if (hModel != nil) {
            
                if (hModel.url == nil) {
                    
             //       NSLog(@"点击了详情");
                    
                    DetailViewController *detailVC = [[DetailViewController alloc] init] ;
                    
                    detailVC.docidStr = hModel.docid;
                    
                    [self.navigationController pushViewController:detailVC animated:YES];
                    
                    [detailVC release];
                    
                }else{
            //        NSLog(@"点击了图集");
                    
                    DetailPictureViewController *picVC = [[DetailPictureViewController alloc] init] ;
                    
                 //   [picVC passValue:hModel.url];
                    
                    picVC.postStr = hModel.url;
                    picVC.tempStr = hModel.url;
                    
                    [self presentViewController:picVC animated:YES completion:nil];
                    [picVC release];
                }

//            }else{
//                
//                UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"暂无网络连接" message:@"请检查网络" delegate:self cancelButtonTitle:nil
//                                                   otherButtonTitles:nil, nil];
//                [av show];
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [av dismissWithClickedButtonIndex:0 animated:YES];
//                    [av release];
//                });
//
//            }
            
        }

    }
}

/*
#pragma mark 点击看看详情页面的button情况
- (void)observeTitleOfButton:(DetailViewController *)DVC model:(HomeModel *)model
{
    
}
*/
#pragma mark 视图中间添加提示字
- (void)addTempTextView
{
    
    //添加加载中的动画
    self.activityIV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] ;
    self.activityIV.center = CGPointMake(100, 20);
    [self.view addSubview:self.activityIV];
    [self.activityIV startAnimating];
    
    self.label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)] autorelease];
    self.label.text = @"加载ing....";
    self.label.textAlignment = NSTextAlignmentCenter;

    [self.view addSubview:self.label];
    
}


#pragma mark 下拉刷新方法
- (void)dragTableDidTriggerRefresh:(UITableView *)tableView
{
    
  //  NSLog(@"qqqqqqqqqqqqrwrwetewtre");
    
    _num = 0;
    [[ShareDataHandle shareDataHandle] parseDataWithCenterKeyString:self.passedStr numberStr:[NSString stringWithFormat:@"%ld",(long)_num]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
       [self.tableView headerEndRefreshing];
        [self.tableView reloadData];
        
    });
}


#pragma mark 上拉加载
- (void)dragTableDidTriggerLoadMore:(UITableView *)tableView
{
    
    _num += 20;
    
    if (_num <= 1000) {
        
        [[ShareDataHandle shareDataHandle] parseDataWithCenterKeyString:self.passedStr numberStr:[NSString stringWithFormat:@"%ld",(long)_num]];
        
    }else{
        
        _num = 0;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
    
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
        
    });

}



- (void)didReceiveMemoryWarning
{
    
    [super didReceiveMemoryWarning];
    //根视图已经加载过,根视图未显⽰示
    if ([self isViewLoaded] == YES && self.view.window
        == nil) {
        //将根视图销毁
        self.view = nil;
    }
    
}







/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
